// 获取UUID
export const getUUID = () => {
  if (typeof crypto === 'object') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID();
    }
    if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
      const callback = (c) => {
        const num = Number(c);
        return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(16);
      };
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, callback);
    }
  }
  let timestamp = new Date().getTime();
  let perforNow = (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let random = Math.random() * 16;
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0;
      timestamp = Math.floor(timestamp / 16);
    } else {
      random = (perforNow + random) % 16 | 0;
      perforNow = Math.floor(perforNow / 16);
    }
    return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
  });
}

/**
 * 时间格式化
 * @param {Date | Timestamp | Timestring} time 需要格式化的时间（Date对象或时间戳、时间字符串）
 * @param {String} 格式
 * @return {String} 返回格式化后的时间
 */
export const formatTime = (time, format = 'YYYY/MM/DD hh:mm:ss') => {
  try {
    const d = new Date(time)
    const year = d.getFullYear()
    const month = d.getMonth() + 1
    const date = d.getDate()
    const hours = d.getHours()
    const minutes = d.getMinutes()
    const seconds = d.getSeconds()
    let result = format
    result = result.replace(/(y|Y){4}/g, year)
    // 前置补零
    result = result.replace(/MM/g, month.toString().padStart(2, '0'))
    result = result.replace(/(d|D){2}/g, date.toString().padStart(2, '0'))
    result = result.replace(/hh/g, hours.toString().padStart(2, '0'))
    result = result.replace(/mm/g, minutes.toString().padStart(2, '0'))
    result = result.replace(/ss/g, seconds.toString().padStart(2, '0'))
    // 不补零
    result = result.replace(/M/g, month)
    result = result.replace(/(d|D)/g, date)
    result = result.replace(/h/g, hours)
    result = result.replace(/m/g, minutes)
    result = result.replace(/s/g, seconds)
    return result
  } catch (err) {
    return err
  }
}

// 格式化钱款，如：1000 -> 1,000.00
export const formatMoney = (money, n = 2) => {
  let s = parseFloat((money + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
  let l = s.split('.')[0].split('').reverse()
  let r = s.split('.')[1]
  let t = ''
  for (let index = 0; index < l.length; index++) {
    t += l[index] + ((index + 1) % 3 == 0 && (index + 1) != l.length ? ',' : '')
  }
  return t.split('').reverse().join('') + '.' + r
}
